blog

Home / DeveloperSection / Blogs / Exception Handling in Java: try-catch statements

Exception Handling in Java: try-catch statements

zack mathews 1611 20-May-2016

We can easily catch and handle errors in our programs so that they do not terminate abnormally. When a program terminates abnormally, typically it dumps some undecipherable messages to the user terminal. Worse is the case where GUI applications terminate abnormally and switch to a console mode, thus totally confusing the user. We better take care of such exceptions in our programs in order to provide a rich user experience.

To catch exception conditions in our program, Java provides a construct called the try-catch block. The susceptible code that may generate an exception at runtime is enclosed in a try block, and the exception-handling code is enclosed in a catch block. The syntax of a try-catch block is shown here

try {

         blockStatements
} catch ( ExceptionType exceptionObjectName ) {
            blockStatements
}

 A try-catch block in your program code looks like this:

try {

        // code that may generate a runtime or some kind of exception
} catch (Exception e) {
        // your error handler
}
 

If an exception occurs while the code in the try block is being executed, the Java runtime creates an object of the Exception class, encapsulating the information on what went wrong, and transfers the program control to the first statement enclosed in the catch block. The code in the catch block analyses the information stored in the Exception object and takes the appropriate corrective action. The exception in the previous example can be handled gracefully by putting the susceptible printVisitorList method in a try-catch block, as shown here:

try {

     roster.printVisitorList();
} catch (Exception e) {
         System.out.println (" Quitting on end of list" );
}

 Now, when we run the program, we will get a more graceful quit message on the terminal at the end of the list. The partial output is shown here:

...
Visitor ID # gc051hh3hba7
Visitor ID # i98ivsnwunp4
Visitor ID # rapll6ouc0m6
Quitting on end of list

 Unfortunately, this error message appears on the terminal in any iteration of the while loop if an error occurs in that iteration, and not necessarily only at the end of the list.

As we can see in this example, the Java runtime always passes an Exception object to our exception handler. Because the types of exceptions or runtime errors that can occur in our application can be very large, it will be difficult to assimilate the information provided by a single Exception object. Therefore, the Exception class is categorized into several subclasses. We learn this categorization in the next post.


Updated 15-Mar-2018

Leave Comment

Comments

Liked By